from openpyxl import load_workbook

from wepapi.models import Department
from wepapi.utils.Pagination import Pagination
from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from django import forms
from django.http import JsonResponse


def depart_list(request):
    """部门列表"""
    departments = Department.objects.all()

    page_object = Pagination(request, departments)
    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 生成页码
    }

    return render(request, 'depart_list.html', context)


def depart_add(request):
    """新增部门"""
    if request.method == "GET":
        return render(request, "depart_add.html")
    # 获取用户post提交过来的数据（roleName输入为空）
    rolename = request.POST.get("rolename")
    print(rolename)
    # 检查 roleName 是否为空
    if not rolename:
        # 添加一个消息，告诉用户角色名称不能为空
        return HttpResponse("角色名称不能为空")
    # 保存到数据库
    Department.objects.create(rolename=rolename)
    return redirect(reverse("depart_list"))


"""删除部门"""


def depart_del(request):
    id = request.GET.get("id")
    Department.objects.filter(id=id).delete()
    return redirect(reverse("depart_list"))
    # return HttpResponse("删除成功")


"""修改部门"""


def depart_edit(request, id):
    if request.method == "GET":
        row_object = Department.objects.filter(id=id).first()
        return render(request, "depart_edit.html", {"row_object": row_object})
    # 根据ID找到数据库中的数据并进行更新
    # request.POST.get("rolename") 获取用户提交的标题
    Department.objects.filter(id=id).update(rolename=request.POST.get("rolename"))
    # 重定向回部门列表
    return redirect(reverse("depart_list"))


def depart_multipart(request):
    """批量上传"""
    # 1.获取用户上传的文件的对象
    file_object = request.FILES.get("exc")
    print(file_object)
    # 2. 对象传递给openpyxl
    wb = load_workbook(file_object)
    sheet = wb.worksheets[0]

    # 3.循环获取每一行数
    for row in sheet.iter_rows(max_row=3):
        text = row[0].value
        exists = Department.objects.filter(rolename=text).exists()
        if exists:
            Department.objects.create(rolename=text)
    return redirect(reverse('depart_list'))
